package com.earogya.springsecurity.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import com.earogya.springsecurity.security.ChangePasswordInterface;

/**
 * Used to Profile requests.
 * 
 * @author Ureka
 */
@Controller
public class ProfileController extends BaseController {
	@Autowired
	private ChangePasswordInterface changePasswordDao;
	
	@RequestMapping(value="/profile/view_profile.do",method=RequestMethod.GET)
	public void showViewProfilePage() {	
		
	}
	
	
	@RequestMapping(value="/profile/change_password.do",method=RequestMethod.GET)
	public void showChangePasswordPage() {	
		
	}
	
	/**
	 * 
	 * Manage change password
	 * 
	 * @param newPassword
	 * @param oldPassword
	 * @return redirect page
	 */
	@RequestMapping(value="/profile/change_password.do",method=RequestMethod.POST)
	public String submitChangePasswordPage(@RequestParam("newPassword") String newPassword,@RequestParam("oldPassword") String oldPassword) {
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String error;
		String username = principal.toString();
		if (principal instanceof UserDetails) {
		  username = ((UserDetails)principal).getUsername();
		}
		
		error=changePasswordDao.changePassword(username, newPassword, oldPassword);
		if(error==""){
		SecurityContextHolder.clearContext();
		return "redirect:/";
		}
		else{
			return "redirect:/profile/change_password.do?message="+error;
		}
		
	}

	
}
